//
//  PNNetWorkTool+OAuth.swift
//  新浪微博
//
//  Created by MBP on 16/5/14.
//  Copyright © 2016年 MBP. All rights reserved.
//

import Foundation

//身份授权
extension PNNetworkTool {
    //身份验证
    var OAuthURL: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    //获取token的网络请求
    func getAccessToken(code: String, finished:([String: AnyObject]?) -> ()) {
        //准备参数, 详见新浪微博文档
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri
        ]
        
        //发送请求
        request(.POST, URLString: urlString, parameters: params) {[weak self] result in
            //判断result 的一部分结果是否存在并转换成字符串
            guard let result = result,
            let success_token = result["access_token"] as? String,
            let uid = result["uid"] as? String else{
                print("数据格式有问题")
                //即使失败, 一定要有回调
                finished(nil)
                return
            }
            self?.loadUser(success_token, uid: uid, finished: { (userDict) -> () in
                guard var userDict = userDict else {
                    print("数据加载错误")
                    //出错回调
                    finished(nil)
                    return
                }
                //循环result
                for (key, value) in result {
                    userDict[key] = value
                }
                //成功回调
                finished(userDict)
            })
        
            
        }
    }
}